const http = require("http");
const fs = require("fs");
const path = require("path");

http.createServer((req,res)=>{
    if(req.url == "/"){
        var filePath = path.join(__dirname, "/index.html");
        var fileContent = fs.readFileSync(filePath);
        res.writeHead(200, {"Content-Type":"text/html;charset=utf8"})
        res.end(fileContent);
        
    }else if(req.url == "/upload"){
        var str = "";
        req.setEncoding("binary");
        req.on("data", (chunk)=>{
            str += chunk;
        })
        req.on("end",()=>{
            var arr = str.split("\r\n");
            var imgArr = arr.slice(4, arr.length-2);
            var imgStr = imgArr.join("\r\n");
            var imgBuf = Buffer.from(imgStr, "binary");
            var date = new Date();
            var d = "";
            d += date.getFullYear() + "" + (date.getMonth()+1) + "" + date.getDate() + "-" + date.getHours() + "-" + date.getMinutes() + "-" + date.getSeconds();
            fs.writeFileSync(path.join(__dirname,"/upload/"+d+".png"), imgBuf, {"encoding": "binary"});
            console.log(date);
        })
        res.end();
    }else if(req.url == "/list"){
        var filePath = path.join(__dirname, "/list.html");
        var fileContent = fs.readFileSync(filePath);
        res.writeHead(200, {"Content-Type":"text/html;charset=utf8"});
        res.end(fileContent);
    }else if(req.url == "/getlist"){
        var filePath = path.join(__dirname, "/upload");
        var dir = fs.readdirSync(filePath);
        res.writeHead(200, {"Content-Type": "text/plain"});
        res.write(JSON.stringify(dir));
        res.end();
    }else if(req.url.indexOf('/upload')>=0 && (req.url.indexOf('.png')>=0 || req.url.indexOf('.jpg')>=0)){
        var filePath = path.join(__dirname, req.url);
        var img = fs.readFileSync(filePath);
        res.writeHead(200, {"Content-Type": "image/png jpg"});
        res.write(img);
        res.end();
    }
}).listen(8001)
console.log("server is listeing 8001")